package com.allan.springboot_wms.service;


import com.allan.springboot_wms.domain.Inv;
import com.allan.springboot_wms.domain.InvExample;
import com.allan.springboot_wms.mapper.InvMapper;
import com.allan.springboot_wms.req.InvQueryReq;
import com.allan.springboot_wms.req.InvSaveReq;
import com.allan.springboot_wms.resp.InvResp;
import com.allan.springboot_wms.resp.PageResp;
import com.allan.springboot_wms.util.CopyUtil;
import com.allan.springboot_wms.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


import javax.annotation.Resource;
import java.util.List;

@Service
public class InvService {

    private static final Logger LOG = LoggerFactory.getLogger(InvService.class);

    //导入雪花算法    Snowflake算法是Twitter发明的一种算法，用于在分布式、高并发环境中，生成64位自增ID。
//    @Resource
//    private SnowFlake snowFlake;
    @Resource
    private InvMapper invMapper;

    public PageResp<InvResp> list(InvQueryReq req) {
        //mybatis的逆向工程中会生成实例及实例对应的example，example用于添加条件，相当于where后面的部分
        //比如criteria.andXxxEqualTo(value)，添加Xxx字段等于value的条件
        InvExample invExample = new InvExample();
        InvExample.Criteria criteria = invExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {  //判断是否为空 不为空有名字的话 按名字来查找
            criteria.andNameLike("%" + req.getName() + "%");
        }
        PageHelper.startPage(req.getPage(), req.getSize()); //就相当于在数据库中加了LIMIT限制
        //先转成inv类然后再遍历得到InvResp
        List<Inv> invList = invMapper.selectByExample(invExample);
        //pageinfo放入得到总页数或总行数,并在日志中打印出
        PageInfo<Inv> pageInfo = new PageInfo<>(invList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());    //一般传给前端传总行数就可
        //列表复制
        List<InvResp> list = CopyUtil.copyList(invList, InvResp.class);
        //把返回的列表添加到PageResp
        PageResp<InvResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public Inv selectById(Integer id, String name){
        return invMapper.selectByPrimaryKey(id, name);
    }

    public void delete(Integer id, String name){
        invMapper.deleteByPrimaryKey(id, name);
    }

    /**
     * 保存（更新或新增）若传进来的id有值则是更新，无值则是新增
     */
    public void save(InvSaveReq req){
        Inv inv = CopyUtil.copy(req, Inv.class);
        if(ObjectUtils.isEmpty(req.getId())){
            //新增
//            inv.setId((int) snowFlake.nextId()); //自己生成ID
            invMapper.insert(inv);
        }else{
            //更新
            invMapper.updateByPrimaryKey(inv);
        }
    }

    public void update(InvSaveReq req){
        Inv inv = CopyUtil.copy(req, Inv.class);
        if(!ObjectUtils.isEmpty(req.getId())){
            invMapper.updateById(inv);
        }

    }
}
